using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Comteck.Winforms {

  /// <summary>
  /// LINQ帮助类
  /// </summary>
  public static class LinqHelper {

    /// <summary>
    /// 动态排序
    /// </summary>
    public static IEnumerable<T> DynamicOrder<T>(this IEnumerable<T> data, List<string> orderings) where T : class {
      var orderedData = data.OrderBy(x => x.GetPropertyDynamic(orderings.First()));
      foreach (var nextOrder in orderings.Skip(1)) {
        orderedData = orderedData.ThenBy(x => x.GetPropertyDynamic(nextOrder));
      }
      return orderedData;
    }
    
    /// <summary>
    /// 获得动态属性
    /// </summary>
    /// <typeparam name="Tobj"></typeparam>
    /// <param name="self"></param>
    /// <param name="propertyName"></param>
    /// <returns></returns>
    public static object GetPropertyDynamic<Tobj>(this Tobj self, string propertyName) where Tobj : class {
      var param = Expression.Parameter(typeof(Tobj), "value");
      var getter = Expression.Property(param, propertyName);
      var boxer = Expression.TypeAs(getter, typeof(object));
      var getPropValue = Expression.Lambda<Func<Tobj, object>>(boxer, param).Compile();
      return getPropValue(self);
    }
  }

}
